package com.qq.ssm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qq.ssm.dao.AppInfoDao;
import com.qq.ssm.dao.AppVersionDao;
import com.qq.ssm.dto.AppInfoDto;
import com.qq.ssm.entity.AppInfo;
import com.qq.ssm.entity.AppVersion;
import com.qq.ssm.service.AppInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

@Service
public class AppInfoServiceImpl implements AppInfoService {

    @Autowired
    AppInfoDao appInfoDao;
    @Autowired
    AppVersionDao appVersionDao;

    @Override
    public PageInfo<AppInfo> getPage(AppInfoDto appInfoDto, Integer pageNum) {
        AppInfo appInfo = new AppInfo();
        BeanUtils.copyProperties(appInfoDto,appInfo);

        PageHelper.startPage(pageNum,6);
        List<AppInfo> appInfos = appInfoDao.queryAllBy(appInfo);
        PageInfo<AppInfo> page = new PageInfo(appInfos);
        return page;
    }

    @Override
    public void saveOrUpdate(AppInfo appInfo) {
        if (appInfo.getId()==null) {
            appInfoDao.insert(appInfo);
        }else{
            appInfoDao.update(appInfo);
        }
    }

    @Override
    public AppInfo selectById(Integer id) {
        return appInfoDao.queryById(Long.valueOf(id));
    }

    @Override
    public void updOnOff(AppInfo appInfo) {
        appInfoDao.update(appInfo);
    }

    @Override
    public void delAppInfo(Integer id, HttpServletRequest request) {
        AppVersion appVersion = new AppVersion();
        appVersion.setAppid(Long.valueOf(id));
        List<AppVersion> appVersions = appVersionDao.queryAllBy(appVersion);
        for (AppVersion version : appVersions) {
            if (version.getDownloadlink() != null){
                String realPath = request.getServletContext().getRealPath(version.getDownloadlink());
                File realPathFile = new File(realPath);
                if (realPathFile.exists())realPathFile.delete();
            }
            appVersionDao.deleteById(version.getId());
        }

        AppInfo appInfo = appInfoDao.queryById(Long.valueOf(id));
        if (appInfo.getLogopicpath() != null){
            String realPath = request.getServletContext().getRealPath(appInfo.getLogopicpath());
            File realFile = new File(realPath);
            if (realFile.exists())realFile.delete();
        }
        appInfoDao.deleteById(Long.valueOf(id));
    }
}
